import sys
import asyncio
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton
import datetime
from rpa.wechat_controller import WeChatController

async def main():
    app = QApplication(sys.argv)
    window = QMainWindow()
    window.setWindowTitle("WeChat RPA 桌面工具")
    window.setGeometry(100, 100, 600, 400)

    central_widget = QWidget()
    layout = QVBoxLayout()

    # 状态标签
    status_label = QLabel("状态: 等待同步...")
    layout.addWidget(status_label)

    whitelist_label = QLabel("白名单用户:")
    layout.addWidget(whitelist_label)

    whitelist_content = QLabel("加载中...")
    layout.addWidget(whitelist_content)

    # 私聊消息回复状态区域
    reply_status_label = QLabel("私聊消息回复状态:")
    layout.addWidget(reply_status_label)

    reply_status_area = QLabel("暂无消息记录")
    reply_status_area.setWordWrap(True)
    layout.addWidget(reply_status_area)

    # 群聊消息回复状态区域
    group_reply_status_label = QLabel("群聊消息回复状态:")
    layout.addWidget(group_reply_status_label)

    group_reply_status_area = QLabel("暂无群聊消息")
    group_reply_status_area.setWordWrap(True)
    layout.addWidget(group_reply_status_area)

    # 文件消息状态区域
    file_status_label = QLabel("文件消息状态:")
    layout.addWidget(file_status_label)

    file_status_area = QLabel("暂无文件消息")
    file_status_area.setWordWrap(True)
    layout.addWidget(file_status_area)

    # 消息历史记录区域
    history_label = QLabel("私聊消息历史记录:")
    layout.addWidget(history_label)

    history_text_area = QLabel("暂无历史消息")
    history_text_area.setWordWrap(True)
    layout.addWidget(history_text_area)

    # 群聊消息历史记录区域
    group_history_label = QLabel("群聊消息历史记录:")
    layout.addWidget(group_history_label)

    group_history_text_area = QLabel("暂无群聊历史消息")
    group_history_text_area.setWordWrap(True)
    layout.addWidget(group_history_text_area)

    # 文件消息历史记录区域
    file_history_label = QLabel("文件消息历史记录:")
    layout.addWidget(file_history_label)

    file_history_text_area = QLabel("暂无文件历史消息")
    file_history_text_area.setWordWrap(True)
    layout.addWidget(file_history_text_area)

    # 消息同步状态区域
    sync_status_label = QLabel("消息同步状态:")
    layout.addWidget(sync_status_label)

    sync_status_area = QLabel("未同步")
    layout.addWidget(sync_status_area)

    sync_button = QPushButton("手动同步白名单")
    layout.addWidget(sync_button)

    central_widget.setLayout(layout)
    window.setCentralWidget(central_widget)
    window.show()

    controller = WeChatController()

    def update_whitelist_display():
        names = [user.username for user in controller.whitelist_users]
        whitelist_content.setText(", ".join(names) if names else "暂无白名单用户")

    def update_reply_status(message="暂无消息记录"):
        reply_status_area.setText(message)

    def update_group_reply_status(message="暂无群聊消息"):
        group_reply_status_area.setText(message)

    def update_sync_status(status="未同步"):
        sync_status_area.setText(status)

    def update_message_history():
        if not controller.message_history:
            history_text_area.setText("暂无历史消息")
            return

        history_str = '\n'.join([
            f"[{msg['timestamp']}] {msg['username']}: {msg['content']} (ID: {msg['userId']})"
            for msg in controller.get_message_history()
        ])
        history_text_area.setText(history_str)

    def update_group_message_history():
        if not controller.group_message_history:
            group_history_text_area.setText("暂无群聊历史消息")
            return

        history_str = '\n'.join([
            f"[{msg['timestamp']}] [{msg['groupName']}] {msg['sender']}: {msg['content']}"
            for msg in controller.get_group_message_history()
        ])
        group_history_text_area.setText(history_str)

    sync_button.clicked.connect(lambda: (
        controller.sync_whitelist_from_backend(),
        update_whitelist_display(),
        update_sync_status("手动同步完成")
    ))

    # 初始同步
    controller.sync_whitelist_from_backend()
    update_whitelist_display()
    status_label.setText("状态: 已就绪")

    # 绑定消息接收事件
    controller.message_received.connect(lambda user: (
        print(f"收到私聊消息: {user.username}"),
        update_reply_status(f"[新消息] 收到来自 {user.username} 的消息，正在处理..."),
        update_message_history(),
        update_sync_status(f"消息已同步到后端 @ {datetime.now().strftime('%H:%M:%S')}")
    ))

    # 绑定群聊消息接收事件
    controller.group_message_received.connect(lambda group_msg: (
        print(f"收到群聊消息: {group_msg['groupName']}", ),
        update_group_reply_status(f"[新群聊] 来自 {group_msg['groupName']}（{group_msg['sender']}）: {group_msg['content']}")
    ))

    # 绑定文件接收事件
    controller.file_received.connect(lambda file_msg: (
        print(f"收到文件: {file_msg['fileName']} from {file_msg['username']}"),
        update_file_status(f"[新文件] 收到来自 {file_msg['username']} 的文件: {file_msg['fileName']} ({file_msg['fileSize']})"),
        update_file_message_history()
    ))

    sys.exit(app.exec_())

if __name__ == '__main__':
    asyncio.run(main())